<?php
/**
 * Created by PhpStorm.
 * User: wjj
 * Date: 2016/11/1
 */

namespace app\logic;


use app\models\Tag;
use yii;


class TagLogic
{
    public static $input_type_list = ['下拉框','输入框','单选项','多选项'];

    public function getTag($query = [], $page = 1, $limit = 10)
    {
        $tag = Tag::find()->filterWhere($query)->orderBy('tag_id desc')
            ->offset(($page - 1) * $limit)->limit($limit);
        $lists = $tag->asArray()->all();
        $return = [
            'lists' => $lists,
            'pager' => [
                'total' => $tag->count(),
                'page' => $page,
                'limit' => $limit,
                'url' => 'tag/index',
                'query' => $query
            ]
        ];
        return $return;
    }

    public function addTag($params)
    {
        $tag = new Tag();
        $tag->tag_name = $params['tag_name'];
        $tag->status = 1;
        $tag->save();
        return true;
    }

    public function editTagById($id, $params)
    {
        if(!$tag = Tag::findOne($id)) return false;
        $tag->tag_name = $params['tag_name'];
        return $tag->save();
    }

    public function getById($id)
    {
        return Tag::find()->where(['tag_id' => $id])->asArray()->one();
    }

    public function deleteById($id)
    {
        $tag = Tag::findOne($id);
        $tag->delete();
        return true;
    }

    public function saveStatus($id)
    {
        $tag = Tag::findOne($id);
        if($tag->status)
            $tag->status = 0;
        else
            $tag->status = 1;
        return $tag->save();
    }

    public function getTagByShop($shop_id){
        return Tag::find()
            ->from('{{%tag}} t')
            ->leftJoin('{{%shop_tag}} st','t.tag_id=st.tag_id')
            ->where("st.shop_id=$shop_id AND t.status=1")
            ->asArray()
            ->all();
    }

    public function getAllTag($ids=0){
        if($ids)
            return Tag::find()->where(['not in','tag_id',$ids])->asArray()->all();
        else
            return Tag::find()->asArray()->all();
    }


}